package service

import (
	"encoding/json"
	"errors"
	"time"

	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/plugin/gva_intelligent_form/model"
	"github.com/flipped-aurora/gin-vue-admin/server/plugin/gva_intelligent_form/model/request"
	"gorm.io/datatypes"
)

type IntelligentFormService struct{}

// CreateIntelligentForm 创建表单
func (s *IntelligentFormService) CreateIntelligentForm(req *request.CreateIntelligentFormRequest, userId uint) (*model.IntelligentForm, error) {
	// 转换配置为JSON
	formConfigBytes, _ := json.Marshal(req.FormConfig)
	themeConfigBytes, _ := json.Marshal(req.ThemeConfig)

	// 设置默认表单类型
	formType := req.FormType
	if formType == "" {
		formType = "normal"
	}

	form := &model.IntelligentForm{
		Title:       req.Title,
		Description: req.Description,
		Status:      0, // 草稿状态
		CreateUser:  userId,
		FormConfig:  datatypes.JSON(formConfigBytes),
		ThemeConfig: datatypes.JSON(themeConfigBytes),
		SubmitLimit: req.SubmitLimit,
		SubmitCount: 0,
		IsPublic:    req.IsPublic,
		Password:    req.Password,
		StartTime:   req.StartTime,
		EndTime:     req.EndTime,
		FormType:    formType,
	}

	err := global.GVA_DB.Create(form).Error
	return form, err
}

// UpdateIntelligentForm 更新表单
func (s *IntelligentFormService) UpdateIntelligentForm(req *request.UpdateIntelligentFormRequest, userId uint) error {
	var form model.IntelligentForm
	err := global.GVA_DB.Where("id = ? AND create_user = ?", req.ID, userId).First(&form).Error
	if err != nil {
		return errors.New("表单不存在或无权限")
	}

	// 转换配置为JSON
	formConfigBytes, _ := json.Marshal(req.FormConfig)
	themeConfigBytes, _ := json.Marshal(req.ThemeConfig)

	updates := map[string]interface{}{
		"title":        req.Title,
		"description":  req.Description,
		"form_config":  datatypes.JSON(formConfigBytes),
		"theme_config": datatypes.JSON(themeConfigBytes),
		"submit_limit": req.SubmitLimit,
		"is_public":    req.IsPublic,
		"password":     req.Password,
		"start_time":   req.StartTime,
		"end_time":     req.EndTime,
		"form_type":    req.FormType,
	}

	return global.GVA_DB.Model(&form).Updates(updates).Error
}

// DeleteIntelligentForm 删除表单
func (s *IntelligentFormService) DeleteIntelligentForm(id uint, userId uint) error {
	var form model.IntelligentForm
	err := global.GVA_DB.Where("id = ? AND create_user = ?", id, userId).First(&form).Error
	if err != nil {
		return errors.New("表单不存在或无权限")
	}

	// 软删除表单
	return global.GVA_DB.Delete(&form).Error
}

// GetIntelligentForm 获取表单详情
func (s *IntelligentFormService) GetIntelligentForm(id uint) (*model.IntelligentForm, error) {
	var form model.IntelligentForm
	err := global.GVA_DB.Where("id = ?", id).First(&form).Error
	return &form, err
}

// GetIntelligentFormList 获取表单列表
func (s *IntelligentFormService) GetIntelligentFormList(info request.IntelligentFormSearch) (list []model.IntelligentForm, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&model.IntelligentForm{})

	// 添加搜索条件
	if info.Title != "" {
		db = db.Where("title LIKE ?", "%"+info.Title+"%")
	}
	if info.Status != 0 {
		db = db.Where("status = ?", info.Status)
	}
	if info.CreateUser != 0 {
		db = db.Where("create_user = ?", info.CreateUser)
	}
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}

	err = db.Count(&total).Error
	if err != nil {
		return
	}

	err = db.Limit(limit).Offset(offset).Order("created_at DESC").Find(&list).Error
	return list, total, err
}

// PublishIntelligentForm 发布表单
func (s *IntelligentFormService) PublishIntelligentForm(id uint, userId uint) error {
	var form model.IntelligentForm
	err := global.GVA_DB.Where("id = ? AND create_user = ?", id, userId).First(&form).Error
	if err != nil {
		return errors.New("表单不存在或无权限")
	}

	return global.GVA_DB.Model(&form).Update("status", 1).Error
}

// CloseIntelligentForm 关闭表单
func (s *IntelligentFormService) CloseIntelligentForm(id uint, userId uint) error {
	var form model.IntelligentForm
	err := global.GVA_DB.Where("id = ? AND create_user = ?", id, userId).First(&form).Error
	if err != nil {
		return errors.New("表单不存在或无权限")
	}

	return global.GVA_DB.Model(&form).Update("status", 2).Error
}

// GetPublicForm 获取公开表单（用于填写）
func (s *IntelligentFormService) GetPublicForm(id uint, password string) (*model.IntelligentForm, error) {
	var form model.IntelligentForm
	err := global.GVA_DB.Where("id = ? AND status = 1", id).First(&form).Error
	if err != nil {
		return nil, errors.New("表单不存在或已关闭")
	}

	// 检查是否为公开表单
	if !form.IsPublic {
		return nil, errors.New("表单为私有表单")
	}

	// 检查密码
	if form.Password != "" && form.Password != password {
		return nil, errors.New("密码错误")
	}

	// 检查时间限制
	now := time.Now()
	if form.StartTime != nil && now.Before(*form.StartTime) {
		return nil, errors.New("表单尚未开始")
	}
	if form.EndTime != nil && now.After(*form.EndTime) {
		return nil, errors.New("表单已结束")
	}

	// 检查提交限制
	if form.SubmitLimit > 0 && form.SubmitCount >= form.SubmitLimit {
		return nil, errors.New("表单提交已达上限")
	}

	return &form, nil
}

// GetGeneratedForm 获取生成的表单（用于填写，专门用于生成类型的表单）
func (s *IntelligentFormService) GetGeneratedForm(id uint, password string) (*model.IntelligentForm, error) {
	var form model.IntelligentForm
	err := global.GVA_DB.Where("id = ? AND status = 1 AND form_type = ?", id, "generated").First(&form).Error
	if err != nil {
		return nil, errors.New("生成表单不存在或已关闭")
	}

	// 生成表单默认为公开，无需检查IsPublic

	// 检查密码
	if form.Password != "" && form.Password != password {
		return nil, errors.New("密码错误")
	}

	// 检查时间限制
	now := time.Now()
	if form.StartTime != nil && now.Before(*form.StartTime) {
		return nil, errors.New("表单尚未开始")
	}
	if form.EndTime != nil && now.After(*form.EndTime) {
		return nil, errors.New("表单已结束")
	}

	// 检查提交限制
	if form.SubmitLimit > 0 && form.SubmitCount >= form.SubmitLimit {
		return nil, errors.New("表单提交已达上限")
	}

	return &form, nil
}
